

//ref: http://www.photoshopessentials.com/photo-editing/photoshop-levels-image-adjustment-essentials/
Shader "Custom/adjustLevels" {
Properties {
	_MainTex ("Base (RGB)", 2D) = "white" {}
	_InputLevelMin("input level min",Range(0,255))=0
	_InputLevelMax("input level max",Range(0,255))=255
	_OutputLevelMin("output level min",Range(0,255))=0
	_OutputLevelMax("output level max",Range(0,255))=255
	_Midtone("midtone",Range (0.10,9.90))=1

}

SubShader {
	Tags { "RenderType"="Opaque" }
	LOD 100
	
	Pass {  
		CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag
			#pragma multi_compile_fog
			
			#include "UnityCG.cginc"

			struct appdata_t {
				float4 vertex : POSITION;
				float2 texcoord : TEXCOORD0;
			};

			struct v2f {
				float4 vertex : SV_POSITION;
				half2 texcoord : TEXCOORD0;
			///	UNITY_FOG_COORDS(1)
			};

			sampler2D _MainTex;
			float4 _MainTex_ST;
			float _InputLevelMin;
			float _InputLevelMax;
			float _OutputLevelMin;
			float _OutputLevelMax;
			float _Midtone;
			v2f vert (appdata_t v)
			{
				v2f o;
				o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
				o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex);
			///	UNITY_TRANSFER_FOG(o,o.vertex);
				return o;
			}
			
			float4 frag (v2f i) : SV_Target
			{
				float4 col = tex2D(_MainTex, i.texcoord);
				float I=clamp(col.r*255,_InputLevelMin,_InputLevelMax);



				float I1=0+(I-_InputLevelMin)*255/(_InputLevelMax-_InputLevelMin);

				float I2=pow(I1/255,1.0/_Midtone)*255;

				float I3=_OutputLevelMin+(I2)*(_OutputLevelMax-_OutputLevelMin)/255;

				float4 finalColor=float4(I3/255,I3/255,I3/255,1);
				return finalColor;


			///	UNITY_APPLY_FOG(i.fogCoord, col);
			///	UNITY_OPAQUE_ALPHA(col.a);
			///	return col;
			}
		ENDCG
	}
}

}
